let timeId = null;
let statusBarHeight = getApp().globalData.navHeight;
const App = getApp()
import {
    url
} from '../../../../modelApi/url_config.js'
Page({
    data: {
        statusBarHeight: statusBarHeight,
        history: [],
        result: [],
        value: '',
        showResult: false,
        loadfinshed: false
    },
    cancelSearch() {
        this.setData({
            showResult: false,
            value: ''
        })
    },
    keywordHandle(e) {
        const text = e.target.dataset.text;
        this.setData({
            value: text,
            showResult: true
        })
        this.searchFunc()
    },
    onLoad() {
        this.loadhistoryFunc()
    },
    loadhistoryFunc() {
        const history = wx.getStorageSync('historyseachlist');
        if (history) {
            this.setData({
                history: Object.prototype.toString.call(history).slice(8,-1) === 'Array' ? history : JSON.parse(history)
            })
        }
    },
    bindconfirm(e) {
        this.setData({
            showResult: true,
            value: e.detail.value
        })
        const historyseachlist = wx.getStorageSync('historyseachlist')
        const histrory = []
        if (!historyseachlist) {
            histrory.push(e.detail.value)
            wx.setStorageSync('historyseachlist', histrory)
        } else {
            const arr1 = Object.prototype.toString.call(historyseachlist).slice(8,-1) === 'Array' ? historyseachlist : JSON.parse(historyseachlist)
            histrory.push(e.detail.value);
            const arr2 = [...arr1, ...histrory];
            let uniq = this.uniq(arr2)
            uniq = uniq.length > 8 && uniq.slice(-8) || uniq
            wx.setStorageSync('historyseachlist', uniq.reverse())
        }
        this.searchFunc(1)
    },
    uniq(array){
        var temp = [];
        for(var i = 0; i < array.length; i++){
            if(temp.indexOf(array[i]) == -1){
                temp.push(array[i]);
            }
        }
        return temp;
    },
    searchFunc(type) {
        const par = {
            searchText: this.data.value
        }
        App.ajax(url.goodsListUrl, par , 'post').then(res => {
            this.setData({
                result: res.rows,
                loadfinshed: true
            })
            type && this.loadhistoryFunc()
        })
    },
    gotoDetail(event) {
        wx.navigateTo({
          url: '/pages/index/sonpages/goods-detail/index?goodsId=' + event.currentTarget.dataset.goodsid,
        })
    }
})